package com.springBoot.utils;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
@RunWith(SpringRunner.class)
public class HttpRequestUtil {

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * @param url    请求url
	 * @param object 请求参数
	 * @param clazz  返回类型
	 */
	public <T> T postRequest(String url, Object object, Class<T> clazz) {
		return restTemplate.postForObject(url, object, clazz);
	}

	/**
	 * @param url   请求url
	 * @param map   请求参数
	 * @param clazz 返回类型
	 */
	public <T> T postRequest(String url, Map<String, Object> map, Class<T> clazz) {
		MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
		if (map != null && !map.isEmpty()) {
			map.forEach(paramMap::add);
		}
		return restTemplate.postForObject(url, paramMap, clazz);
	}
}
